package com.kfm.jdbc.day01;

import java.sql.*;

public class Demo01 {

    public static void main(String[] args) {
        insert();
    }


    public static int insert() {


        String deptName = "法务部";
        String sql = "insert into dept (deptname) values('%s')".formatted(deptName);

        try ( // 获取连接
              Connection connection = getConnection();
              // 执行操作
              Statement statement = connection.createStatement();) {

            int rows = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

            if (rows > 0) {
                System.out.println("执行成功");
                // 获取自增长值
                ResultSet generatedKeys = statement.getGeneratedKeys();

                if (generatedKeys.next()) {
                    System.out.println(generatedKeys.getObject(1));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return 0;
    }


    private static Connection getConnection() {
        // 注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        // 获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/company_info";
        String user = "root";
        String password = "root";

        try {
            Connection connection = DriverManager.getConnection(url, user, password);
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
